const db = uniCloud.database();
const dbCmd = db.command;
const $ = db.command.aggregate;
module.exports = async function(options = {}) {
	const { groupCode, startTime, endTime } = options;
	const token = this.getUniIdToken();
	if (!token || !groupCode || !startTime || !endTime) {
		throw new Error('非法访问');
	}
	let [res] = await Promise.all([
		db.collection('a-dz-group-list')
		.aggregate()
		.match({
			groupCode
		})
		.lookup({
			from: 'a-dz-group-apply-list',
			let: {
				mainid: '$groupCode'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
					$.eq(['$groupCode', '$$mainid']),
					$.eq(['$applyStatus', 'AGREE'])
				])))
				.lookup({
					from: 'a-dz-complete-stats-list',
					let: {
						mainid: '$characterId'
					},
					pipeline: $.pipeline().match(dbCmd.expr($.and([
							$.eq(['$characterId', '$$mainid']),
							$.gte(['$createTime', startTime]), // 大于等于startTime
							$.lte(['$createTime', endTime]) // 小于等于endTime
						])))
						.done(),
					as: 'completeList'
				})
				.done(),
			as: 'groupUsers'
		})
		.unwind('$groupUsers')
		.unwind({
			path: '$groupUsers.completeList',
			preserveNullAndEmptyArrays: true // 保留空数组
		})
		.group({
			_id: {
				uid: '$groupUsers.uid',
				characterId: '$groupUsers.characterId',
				nickname: '$groupUsers.nickname',
				avatar: '$groupUsers.avatar'
			},
			kpm: { $avg: {$ifNull: ['$groupUsers.completeList.kpm', 0]} },
			successWpm: { $avg: {$ifNull: ['$groupUsers.completeList.successWpm', 0]} },
			wpm: { $avg: {$ifNull: ['$groupUsers.completeList.wpm', 0]} },
			accuracyKey: { $avg: {$ifNull: ['$groupUsers.completeList.accuracyKey', 0]} },
			totalAccuracyKey: { $sum: '$groupUsers.completeList.accuracyKey' },
			totalAccuracyWord: { $sum: '$groupUsers.completeList.accuracyWord' },
			count: {
				$sum: 1
			},
			learningTime: { $sum: '$groupUsers.completeList.consumingTime' }
		})
		.project({
			_id: 0,
			uid: '$_id.uid',
			characterId: '$_id.characterId',
			nickname: '$_id.nickname',
			avatar: '$_id.avatar',
			kpm: 1,
			successWpm: 1,
			wpm: 1,
			accuracyKey: 1,
			learningTime: 1,
			accuracy: {
				$divide: [
					{ $add: ['$totalAccuracyKey', '$totalAccuracyWord'] },
					{ $multiply: ['$count', 2] }
				]
			}
		})
		.sort({
		  successWpm: -1
		})
		// 使用$group将所有计算结果重新组合成一个数组
		.group({
			_id: null,
			groupUsers: {
				$push: '$$ROOT'
			}
		})
		.project({
			groupUsers: 1,
			_id: 0
		})
		.end()
	])
	const result = res.data.length ? res.data[0].groupUsers : [];
	return {
		code: 0,
		data: result,
		msg: '获取成功'
	}
}